package ttsclient

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"os"

	"github.com/astaxie/beego/logs"
	"github.com/micro/go-micro/errors"
	"strconv"
)

func hashFile(text string) string {

	signByte := []byte(text)
	hash := md5.New()
	hash.Write(signByte)
	return hex.EncodeToString(hash.Sum(nil))
}

func getArgValueInt(k string, args map[string]interface{}) (int, error) {

	if v, ok := args[k]; ok {
		switch v.(type) {
		case string:

			return strconv.Atoi(v.(string))
		case float32:

			return strconv.Atoi(fmt.Sprintf("%.0f", v.(float32)))
		case float64:
			return strconv.Atoi(fmt.Sprintf("%.0f", v.(float64)))
		case int:
			return v.(int), nil
		case int64:
			return int(v.(int64)), nil
		case int32:
			return int(v.(int32)), nil
		}
	}
	return 0, errors.New("100901", "now keys", -1)

}

func createCacheFilePath(text string, volume, speed float64, voiceType int) string {
	hashStr := fmt.Sprintf("%s_%.1f_%.1f_%d", text, volume, speed, voiceType)

	file := hashFile(hashStr)

	return audioDir + "/" + file + ".wav"
}

func createCacheFileName(text string, volume, speed float64, voiceType int) string {
	hashStr := fmt.Sprintf("%s_%.1f_%.1f_%d", text, volume, speed, voiceType)

	return hashFile(hashStr)
}

func getCacheFile(text string, volume, speed float64, voiceType int) (string, error) {

	hashStr := fmt.Sprintf("%s_%.1f_%.1f_%d", text, volume, speed, voiceType)

	logs.Debug("hash string:%v", hashStr)
	file := hashFile(hashStr)

	name := audioDir + "/" + file + ".wav"
	_, err := os.Stat(name)
	if err != nil {
		if os.IsNotExist(err) {
			return name, err
		}

		return name, err
	}

	return name, nil
}
